package com.hbfk.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpClient {

	private static final Log logger = LogFactory.getLog(HttpClient.class);
	
	private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
	private final static String DEFAULT_ENCODING = "UTF-8";
	 
	private static String charset = "UTF-8";
	
	//redis微服务相关路径
		private static final String redisurl=ResourceBundle.getBundle("redis").getString("redisurl").toString();

		public static final String HTTPPUT = "put";

		public static final String HTTPPOST = "post";

		public static final String HTTPGET = "get";
	
	/**
	 * 获取子公司树
	 */
	public static String getOrgChildrenUrl =redisurl+"/redis/getOrgChildren";
	
	
	// 此方法是POST请求上传的参数中包含本地图片信息File类型
		public static String request(String url, HashMap<String, Object> fields, HashMap<String, File> files) throws Exception {

		
			CloseableHttpClient httpClient = HttpClients.createDefault();
			CloseableHttpResponse response = null;
			String result = null;
			// HttpClient请求的相关设置，可以不用配置，用默认的参数，这里设置连接和超时时长(毫秒)
			//RequestConfig config = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
			try {
				MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
				if(fields!=null){
					addFields(entityBuilder, fields);
				}
				if(files!=null){
					addFiles(entityBuilder, files);
				}
		
		
		
				HttpPost httpPost = new HttpPost(url);
				HttpEntity reqEntity = entityBuilder.build();
				httpPost.setEntity(reqEntity);
				//httpPost.setConfig(config);
				// 执行网络请求并返回结果
				response = httpClient.execute(httpPost);
				HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				result = streamToString(resEntity.getContent(), charset);
			}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
				httpClient.close();
			}
			// 得到的是JSON类型的数据需要第三方解析JSON的jar包来解析
			return result;
		}

		// 此方法是把传进的字节流转化为相应的字符串并返回，此方法一般在网络请求中用到
		private static String streamToString(InputStream inputStream, String charset) throws Exception {
			StringBuilder stringBuilder = new StringBuilder();
			try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset)) {
				try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
					String line = null;
					while ((line = reader.readLine()) != null) {
						stringBuilder.append(line).append("\r\n");
					}
				}
			}
			return stringBuilder.toString();
		}
		
		private static void addFields(MultipartEntityBuilder entityBuilder, HashMap<String, Object> fields) {
			for (String name : fields.keySet()) {
				if(fields.get(name)!=null){
					String value = fields.get(name).toString();
					ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
					StringBody StringBody = new StringBody(value,contentType);
					entityBuilder.addPart(name, StringBody);
				}
			}
		}
		
		private static void addFiles(MultipartEntityBuilder entityBuilder, HashMap<String, File> files) {
			
			if (files == null) {
				return;
			}
			for (String name : files.keySet()) {
				File file = files.get(name);
				FileBody fileBody = new FileBody(file);
				entityBuilder.addPart(name, fileBody);
			}
		}

		public static String httpPutClient(String url, HashMap<String, Object> filedMap,
				Map<String, String> headerMap) throws Exception {
			CloseableHttpResponse response = null;// 响应类,
			CloseableHttpClient httpClient = HttpClients.createDefault();
			String result = null;
			
			try {
				URIBuilder builder = new URIBuilder(url);
				
				if(!filedMap.isEmpty()) {
					for (String filed : filedMap.keySet()) {
						builder.addParameter(filed, filedMap.get(filed).toString());
					}
				}
				URI uri = builder.build();
				HttpPut httpPut = new HttpPut(uri); //请求url
				
				if (!headerMap.isEmpty()) {
					for (Map.Entry<String, String> vo : headerMap.entrySet()) {
						httpPut.setHeader(vo.getKey(), vo.getValue());
					}
				}
				
				response = httpClient.execute(httpPut);
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = streamToString(resEntity.getContent(), charset);
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
				httpClient.close();
			}
			return result;
		}

		public static String httpPostClient(String url, HashMap<String, Object> filedMap,
				Map<String, String> headerMap) throws Exception {
			CloseableHttpResponse response = null;// 响应类,
			CloseableHttpClient httpClient = HttpClients.createDefault();
			String result = null;
			
			try {
				HttpPost httpPost = new HttpPost(url); //请求url
				List<NameValuePair> params = new ArrayList<NameValuePair>(0);
				if (!filedMap.isEmpty()) {
					for (Map.Entry<String, Object> parameter : filedMap.entrySet()) {
						params.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue().toString()));
					}
				}
				httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
				
				if (!headerMap.isEmpty()) {
					for (Map.Entry<String, String> vo : headerMap.entrySet()) {
						httpPost.setHeader(vo.getKey(), vo.getValue());
					}
				}
				
				response = httpClient.execute(httpPost);
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = streamToString(resEntity.getContent(), charset);
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
				httpClient.close();
			}
			return result;
		}

		public static String httpGetClient(String url, HashMap<String, Object> filedMap,
				Map<String, String> headerMap) throws Exception {
			CloseableHttpResponse response = null;// 响应类,
			CloseableHttpClient httpClient = HttpClients.createDefault();
			String result = null;
			
			try {
				URIBuilder builder = new URIBuilder(url);
				
				if(!filedMap.isEmpty()) {
					for (String filed : filedMap.keySet()) {
						builder.addParameter(filed, filedMap.get(filed).toString());
					}
				}
				URI uri = builder.build();
				HttpGet httpGet = new HttpGet(uri); //请求url
				
				if (!headerMap.isEmpty()) {
					for (Map.Entry<String, String> vo : headerMap.entrySet()) {
						httpGet.setHeader(vo.getKey(), vo.getValue());
					}
				}
				
				response = httpClient.execute(httpGet);
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = streamToString(resEntity.getContent(), charset);
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
				httpClient.close();
			}
			return result;
		}

		public static String httpPostLoginClient(String url, HashMap<String, String> filedMap,
				Map<String, String> headerMap) throws Exception {
			CloseableHttpResponse response = null;// 响应类,
			CloseableHttpClient httpClient = HttpClients.createDefault();
			String result = null;
			
			try {
				HttpPost httpPost = new HttpPost(url); //请求url
				List<NameValuePair> params = new ArrayList<NameValuePair>(0);
				if (!filedMap.isEmpty()) {
					for (Map.Entry<String, String> parameter : filedMap.entrySet()) {
						params.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue()));
					}
				}
				httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
				
				if (!headerMap.isEmpty()) {
					for (Map.Entry<String, String> vo : headerMap.entrySet()) {
						httpPost.setHeader(vo.getKey(), vo.getValue());
					}
				}
				
				response = httpClient.execute(httpPost);
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = streamToString(resEntity.getContent(), charset);
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
				httpClient.close();
			}
			return result;
		}

}
